package cn.bgw.springboot.lab33.shirodemo.config;

import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    @Bean
    public Realm realm(){
        SimpleAccountRealm realm = new SimpleAccountRealm();
        realm.addAccount("admin", "admin", "ADMIN");
        realm.addAccount("normal", "normal", "NORMAL");
        return realm;
    }

    @Bean
    public DefaultWebSecurityManager securityManager(){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(this.realm());
        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        // 创建 shiroFilterFactoryBean 对象, 用于创建 shiroFilter 过滤器;
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();

        // 2 设置 SecurityManager
        filterFactoryBean.setSecurityManager(this.securityManager());

        // 3 设置 urls
        filterFactoryBean.setLoginUrl("/login"); // 登录 URL
        filterFactoryBean.setSuccessUrl("/login_success"); // 登录成功 URL
        filterFactoryBean.setUnauthorizedUrl("/unauthorized"); // 无权限 URL

        // 4 设置 URL 的权限配置;
        filterFactoryBean.setFilterChainDefinitionMap(this.filterChainDefinitionMap());
        return filterFactoryBean;
    }

    private Map<String, String> filterChainDefinitionMap(){
        Map<String, String> filterMap = new LinkedHashMap();
        filterMap.put("/test/echo", "anon"); // 允许匿名访问;
        filterMap.put("/test/admin", "roles[ADMIN]");
        filterMap.put("/test/normal", "roles[NORMAL]");
        filterMap.put("/logout", "logout");
        filterMap.put("/**", "authc"); // 剩余对的URL, 需要经过认证;
        return filterMap;
    }
}
